package com.simple.aspect;

import java.lang.reflect.Method;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;

import com.simple.annotation.Log;
import com.simple.entity.SysUserLog;
import com.simple.service.SysUserLogService;
import com.simple.utils.HttpContextUtils;
import com.simple.utils.IPUtils;
import com.simple.utils.SysConfig;

/**
 * 用户记录切面
 * 
 */
@Aspect
@Component
public class SysUserLogAspect {

	@Autowired
	SysUserLogService  sysUserLogService;
	
	@Pointcut("@annotation(com.simple.annotation.Log)")
	public void sysUserLog() {}
	
	@Around("sysUserLog()")
	public Object aroundLog(ProceedingJoinPoint point) {
		Object object=null;
		String username=SysConfig.getUsername();//此前获取用户名，用于退出参数
		try {
			object=point.proceed();
		} catch (Throwable e) {
			e.printStackTrace();
		}
		saveLog(point,username);
		return object;
	}
	
	public void saveLog(ProceedingJoinPoint point,String username) {
		MethodSignature methodSignature = (MethodSignature) point.getSignature();
		Method method = methodSignature.getMethod();
		SysUserLog sysUserLog=new SysUserLog();
		Log log=method.getAnnotation(Log.class);
		if(log!=null) {
			sysUserLog.setOperation(log.value());
		}
		if(StringUtils.isNotBlank(username)) {
			sysUserLog.setUsername(username);
		}else {
			Object[] args = point.getArgs();
	        // 请求的方法参数名称
	        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
	        String[] paramNames = u.getParameterNames(method);
	        if (args != null && paramNames != null) {
	            for (int i = 0; i < args.length; i++) {
	                if(paramNames[i].equals("username")) {
	                	sysUserLog.setUsername(args[i].toString());
	                }
	            }
	        }
		}
		HttpServletRequest  request=HttpContextUtils.getHttpServletRequest();
        sysUserLog.setIp(IPUtils.getIpAddr(request)); 
        sysUserLog.setCreateDate(new Date());
        sysUserLogService.saveAndFlush(sysUserLog);
	}
}
